package ch.fusun.baron.clientapp;

import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;

import ch.fusun.baron.client.rmi.ClientService;
import ch.fusun.baron.clientapp.login.LoginDialog;
import ch.fusun.baron.clientapp.messages.Messages;
import ch.fusun.baron.core.injection.Inject;
import ch.fusun.baron.core.injection.ReInjector;

/**
 * Workbench window advisor
 */
public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {

	@Inject
	private ClientService gameClient;

	/**
	 * Constructor
	 * 
	 * @param configurer
	 */
	public ApplicationWorkbenchWindowAdvisor(
			IWorkbenchWindowConfigurer configurer) {
		super(configurer);
	}

	@Override
	public ActionBarAdvisor createActionBarAdvisor(
			IActionBarConfigurer configurer) {
		return new ApplicationActionBarAdvisor(configurer);
	}

	@Override
	public void preWindowOpen() {
		ReInjector.getInstance().reInject(this);
		boolean connected = false;
		while (!connected) {
			InputDialog inputDialog = new InputDialog(new Shell(),
					Messages.ApplicationWorkbenchWindowAdvisor_HostTitle,
					Messages.ApplicationWorkbenchWindowAdvisor_HostDescription,
					Messages.ApplicationWorkbenchWindowAdvisor_HostDefault,
					null);
			inputDialog.open();
			if (inputDialog.getReturnCode() == InputDialog.OK) {
				connected = getGameClient().connectToServer(
						inputDialog.getValue());
			} else {
				new MessageDialog(
						new Shell(),
						Messages.ApplicationWorkbenchWindowAdvisor_ConnectionFailedTitle,
						null,
						Messages.ApplicationWorkbenchWindowAdvisor_ConnectionFailedDescription,
						0,
						new String[] { Messages.ApplicationWorkbenchWindowAdvisor_ConnectionFailedText },
						0).open();
				System.exit(0);
			}
		}
		new LoginDialog(null, getGameClient()).open();

		IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
		configurer.setInitialSize(new Point(600, 600));
		configurer.setShowCoolBar(true);
		configurer.setShowMenuBar(true);
		configurer.setShowStatusLine(true);
	}

	@Override
	public boolean preWindowShellClose() {
		return super.preWindowShellClose();
	}

	/**
	 * @return the gameClient
	 */
	public ClientService getGameClient() {
		return gameClient;
	}
}
